package jin.chen.service.impl;

import jin.chen.mapper.StuMapper;
import jin.chen.mapper.UsersMapper;
import jin.chen.pojo.Stu;
import jin.chen.pojo.Users;
import jin.chen.pojo.bo.UsersBo;
import jin.chen.service.StuService;
import jin.chen.service.UserService;
import jin.chen.utils.DateUtil;
import jin.chen.utils.MD5Utils;
import jin.chen.utils.enums.SexEnum;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private Sid sid;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
       Users users =  usersMapper.selectOneByExample(example);
        return users == null ? false : true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUsers(UsersBo usersBo) {
        String username = usersBo.getUsername();
        String password = usersBo.getPassword();
        //选中代码，按ctrl + shift + t  可以直接try catch
        String pwd = "";
        String id = sid.nextShort();
        try {
            pwd = MD5Utils.getMD5Str(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Users users = new Users();
        users.setUsername(username);
        users.setPassword(pwd);
        users.setNickname(username);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());
        users.setBirthday(DateUtil.stringToDate("1901-01-01"));
        users.setId(id);
        users.setSex(SexEnum.secret.getType());
        users.setFace("http://www.wyh21.cn/userFace.jpg");

        int count = usersMapper.insert(users);
        return count > 0 ? users : null;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {
        String pwd = "";
        try {
            pwd = MD5Utils.getMD5Str(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        criteria.andEqualTo("password", pwd);
        Users users =  usersMapper.selectOneByExample(example);
        return users == null ? null : users;
    }
}
